package com.qf.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author lixu
 */
@RestController
@RequestMapping("/upload")
public class UploadFileController {

    /**
     * 上传文件
     *
     *  返回值  OK 到浏览器页面上
     * 1、 <form action="/upload/test1" method="post" enctype="multipart/form-data">
     *     file: <input type="file" name="file"/> <br>
     *     <input type="submit" value="提交"/>
     *     </form>
     *
     * 2、绑定的时候  ：  配置上传文件解析器  springmvc.xml
     *
     * 3、MultipartFile file ： 形参
     *
     */
    @PostMapping("/test1")
    public String test1(MultipartFile file) throws Exception{

        System.out.println("原始名称：" + file.getOriginalFilename());
        System.out.println("文件的大小：" + file.getSize());
        byte[] bytes = file.getBytes();
        InputStream inputStream = file.getInputStream();
        //扩展名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = UUID.randomUUID().toString() + "." + ext;
        //保存文件或图片   webapp
        file.transferTo(new File("D:\\upload\\" + fileName));
        return "OK";
    }
}
